<?php
/*
 * 扩展工具函数
 * @package    vender
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 6bd34fe6fbbf80937afda8af6d12354bfc811b5f $
 */

defined('IN_IXDCW') or exit('Access Denied');

/**
 * 扩展函数
 * Class Ext
 */
class Ext{

	/**
	 * guid 生成函数
	 * @return string
	 */
	public static function guid() {
		if (function_exists('com_create_guid')) {
			return com_create_guid();
		} else {
			mt_srand((double)microtime() * 10000); //optional for php 4.2.0 and up.
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45); // "-"
			$uuid   = chr(123) // "{"
				. substr($charid, 0, 8) . $hyphen
				. substr($charid, 8, 4) . $hyphen
				. substr($charid, 12, 4) . $hyphen
				. substr($charid, 16, 4) . $hyphen
				. substr($charid, 20, 12)
				. chr(125); // "}"
			return $uuid;
		}
	}

	/**
	 * 生成递归数列
	 * @param        $items 条目
	 * @param string $id    id键
	 * @param string $pid   父级元素
	 * @param string $son   子元素
	 * @return array        返回的排序好的数组
	 */
	public static function genTree($items,$id='arid',$pid='parentid',$son = 'children'){
		$tree = array(); //格式化的树
		$tmpMap = array();  //临时扁平数据

		foreach ($items as $item) {
			$tmpMap[$item[$id]] = $item;
		}

		foreach ($items as $item) {
			if (isset($tmpMap[$item[$pid]])) {
				$tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
			} else {
				$tree[] = &$tmpMap[$item[$id]];
			}
		}
		unset($tmpMap);
		return $tree;
	}

	/**
	 * 生成分类树HTML
	 * @param array        分类数组
	 * @return string      生成HTML
	 */
	public static function categoryHtml($arr) {
		if(!$arr[0]['parentid']){
			echo "<ul>";
		}else{
			echo "<ul class='fn-hide'>";
		}
		foreach($arr as  $v) {
			if( isset($v['children']) && is_array($v['children'])){
				if(!($v['parentid'])){
					echo "<li class='root'><i class='plus'></i><input id=".$v['catid']." type='checkbox' value=".$v['catname']."><label for=".$v['catid'].">".$v['catname']."</label>";
				}else{
					echo "<li><i class='plus'></i><input id=".$v['catid']." type='checkbox' value=".$v['catname']."><label for=".$v['catid'].">".$v['catname']."</label>";
				}
				self::categoryHtml($v['children']);
				echo "</li>";
			}else{
				echo "<li><input id=".$v['catid']." type='checkbox' value=".$v['catname']."><label for=".$v['catid'].">".$v['catname']."</label></li>";
			}
		}
		echo "</ul>";
	}
}